<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      v-model="form"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-upload2" @click="handleImport">导入</el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
      <template slot-scope="{ row }" slot="sattus">
        <el-tag :class="row.status ? 'successTag' : 'dangerTag'">{{ row.status ? '是' : '否' }}</el-tag>
      </template>
      <template slot-scope="{ row }" slot="fifoRequired">
        <el-tag :class="row.fifoRequired ? 'successTag' : 'dangerTag'">{{ row.fifoRequired ? '是' : '否' }} </el-tag>
      </template>
      <template slot="sequenceDefinitionNameForm">
        <el-input placeholder="请选择 条码规则" v-model="form.sequenceDefinitionName" class="input-with-select" disabled>
          <el-button
            slot="append"
            icon="el-icon-circle-close"
            v-if="form.sequenceDefinitionName"
            @click="
              form.sequenceDefinitionName = '';
              form.sequenceDefinitionId = '';
            "
          ></el-button>
          <el-button slot="append" icon="el-icon-search" @click="openSquenceModal"></el-button>
        </el-input>
      </template>
      <template slot="locationNameForm">
        <el-input placeholder="请选择 地址" v-model="form.locationName" class="input-with-select" disabled>
          <el-button
            slot="append"
            icon="el-icon-circle-close"
            v-if="form.locationName"
            @click="
              form.locationName = '';
              form.locationId = '';
            "
          ></el-button>
          <el-button slot="append" icon="el-icon-search" @click="openLocationCommonModal"></el-button>
        </el-input>
      </template>
    </avue-crud>
    <importDialogComp
      title="库存中心导入"
      url="/api/mes-admin/inventory/import"
      export-name="库存中心导入模板.xlsx"
      :visible.sync="importConfig.show"
      @submit="codeClose"
    ></importDialogComp>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/admin/warehouse';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import importDialogComp from '@/components/dialog/import/index.vue';
import { validateContacts } from '@/mixins/validateContacts.js';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'AdminWarehouse',
  components: {
    CommonModalTemplate,
    importDialogComp,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'ADMIN_WAREHOUSE',
      importConfig: {
        show: false
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      tableOption: {},
      timer: new Date().getTime(),
      selectionList: [],
      data: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 130,
        border: true,
        index: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        selection: true,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '仓库类型',
            prop: 'inventoryType',
            search: true,
            type: 'select',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=inventory_type',
            rules: [
              {
                required: true,
                message: '请选择仓库类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '子属性',
            prop: 'subType',
            type: 'select',
            value: 'GENERAL',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=warehouse_sub_type',
            rules: [
              {
                required: true,
                message: '请选择子属性',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '物料存储类型',
            prop: 'partCategories',
            type: 'tree',
            multiple: true, //是否多选
            checkStrictly: true, //在显示复选框的情况下，是否严格的遵循父子不相互关联的做法
            dicUrl: '/api/mes-admin/part-category/tree',
            placeholder: '物料存储类型',
            props: {
              label: 'title',
              value: 'id'
            }
          },
          {
            label: '管理储物先进先出',
            prop: 'fifoRequired',
            type: 'switch',
            value: false,
            labelWidth: 150,
            align: 'center',
            labelTip: '根据物料生产日期控制出库顺序',
            dicData: [
              {
                label: '否',
                value: false
              },
              {
                label: '是',
                value: true
              }
            ]
          },
          {
            label: '条码规则',
            prop: 'sequenceDefinitionName'
          },
          {
            label: '地址',
            prop: 'locationName'
          },
          {
            label: '负责人',
            prop: 'principal',
            type: 'select',
            dicUrl: `/api/blade-system/user/user-list`,
            props: {
              label: 'name',
              value: 'id'
            }
          },
          {
            label: '联系方式',
            prop: 'contacts',
            rules: [{ validator: validateContacts, trigger: 'blur' }]
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            align: 'center',
            value: 1,
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ],
            rules: [
              {
                required: true,
                message: '请选择启用状态',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '备注',
            prop: 'remark'
          }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.warehouse_add, false),
        viewBtn: this.vaildData(this.permission.warehouse_view, false),
        delBtn: this.vaildData(this.permission.warehouse_delete, false),
        editBtn: this.vaildData(this.permission.warehouse_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });
  },
  methods: {
    codeClose(value) {
      if (value) {
        this.onLoad(this.page);
      }
    },
    rowSave(row, done, loading) {
      row.partCategories = row.partCategories.join(',');
      row.partCategories = row.partCategories ? row.partCategories : null;
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      Array.isArray(row.partCategories) ? (row.partCategories = row.partCategories.join(',')) : '';
      // row.partCategories = row.partCategories ? row.partCategories : null;
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    /**
     * 选择模态框行数据
     */
    getSelectedRows(rowData, title) {
      if (title === 'sequenceInfo') {
        this.form['sequenceDefinitionId'] = rowData.id;
        this.form['sequenceDefinitionName'] = rowData.name;
      } else {
        this.form.locationId = this._get(rowData, 'id', '');
        this.form.locationName = this._get(rowData, 'name', '');
      }
    },
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    /**
     * 打开序列号模态框
     */
    openSquenceModal() {
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择序列号规则信息（双击进行选择）',
        url: '/api/mes-admin/sequencedefinition/page',
        isPage: true,
        titleInfo: 'sequenceInfo',
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '规则名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入序列号规则名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入序列号规则编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '序列号规则',
            prop: 'sequenceNoFormat',
            labelslot: true,
            rules: [
              {
                required: true,
                message: '请输入序列号规则',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '规则位数',
            prop: 'charactersCount',
            rules: [
              {
                required: false,
                message: '请输入序列号规则位数',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    /**
     * 打开位置管理选择模态框
     */
    openLocationCommonModal() {
      this.modalName = 'locationModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择位置信息（双击进行选择）',
        url: '/api/mes-admin/location/page?status=0',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '地址名称',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '国家',
            prop: 'country',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '省份',
            prop: 'province'
          },
          {
            label: '城市',
            prop: 'city'
          }
        ]
      };
    },
    handleImport() {
      this.importConfig.show = true;
    }
  }
};
</script>

<style></style>
